package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.UploadPicService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.UploadPicResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.QuanZiVo;
import com.tanhua.server.enums.IdType;
import com.tanhua.server.vo.Dynamic;
import com.tanhua.server.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class QuanZiService {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private UploadPicService uploadPicService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private IdService idService;

    public PageResult queryPublishList(Integer page, Integer pageSize, String token) {
        //分析：通过dubbo中的服务查询用户的好友动态
        //通过mysql查询用户的信息，回写到结果对象中（QuanZiVo）

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //校验token是否有效
        User user = this.userService.queryUserByToken(token);
        if (user == null) {
            //token已经失效
            return pageResult;
        }

        //通过dubbo查询数据
        PageInfo<Publish> pageInfo = this.quanZiApi.queryPublishList(user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
            quanZiVoList.add(quanZiVo);
        });

        //查询用户信息
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(userIds);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            //找到对应的用户信息
            for (UserInfo userInfo : userInfoList) {
                if (quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    this.fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }

        pageResult.setItems(quanZiVoList);
        return pageResult;
    }

    /**
     * 填充用户信息
     *
     * @param userInfo
     * @param quanZiVo
     */
    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo) {
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));

        quanZiVo.setCommentCount(0); //TODO 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        quanZiVo.setHasLiked(0); //TODO 是否点赞（1是，0否）
        quanZiVo.setLikeCount(0); //TODO 点赞数
        quanZiVo.setHasLoved(0); //TODO 是否喜欢（1是，0否）
        quanZiVo.setLoveCount(0); //TODO 喜欢数
    }

    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        PageInfo<Publish> pageInfo = quanZiApi.queryRecommendPublishList(user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        pageResult.setItems(fillQuanZiVo(records));
        return pageResult;
    }

    private List<QuanZiVo> fillQuanZiVo(List<Publish> records) {
        List<QuanZiVo> quanZiVoListlist = new ArrayList<>();
        records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
            quanZiVoListlist.add(quanZiVo);
        });
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(userIds);
        for (QuanZiVo quanZiVo : quanZiVoListlist) {
            for (UserInfo userInfo : userInfoList) {
                if (quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }
        return quanZiVoListlist;
    }

    public String savePublish(String textContent, String location, String latitude, String longitude, MultipartFile[] multipartFile) {
        //查询当前的登录信息
        User user = UserThreadLocal.get();

        Publish publish = new Publish();
        publish.setId(ObjectId.get());
        publish.setUserId(user.getId());
        Long autoPid = idService.createAutoId(IdType.PUBLISH);
        publish.setPid(autoPid);
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setSeeType(1);
        publish.setCreated(System.currentTimeMillis());

        List<String> picUrls = new ArrayList<>();
        //图片上传
        for (MultipartFile file : multipartFile) {
            UploadPicResult picUploadResult = this.uploadPicService.uploadPic(file);
            picUrls.add(picUploadResult.getName());
        }

        publish.setMedias(picUrls);
        return quanZiApi.savePublish(publish, user.getId());
    }

    public Integer dynamicLikes(String publishId) {
        Integer likeCount = null;
        try {
            Long userId = UserThreadLocal.get().getId();
            //如果已经被点赞过,就不能再点赞
            boolean isLiked = quanZiApi.queryCommentType(publishId, userId);
            if (isLiked) {
                return likeCount;
            }
            //点赞就是往comment集合中添加一条数据
            likeCount = quanZiApi.saveLiked(publishId, userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return likeCount;
    }

    public Integer cancleLike(String publishId) {
        Integer likeCount = null;
        try {
            Long userId = UserThreadLocal.get().getId();
            //如果没有被点赞,就不能取消点赞
            boolean isLiked = quanZiApi.queryCommentType(publishId, userId);
            if (!isLiked) {
                return likeCount;
            }
            //取消点赞就是往comment集合中删除那条数据
            likeCount = quanZiApi.deleteLiked(publishId, userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return likeCount;
    }

    public Integer loveComment(String publishId) {
        Integer loveCount = null;
        try {
            Long userId = UserThreadLocal.get().getId();
            //如果已经被喜欢过,就不能再喜欢
            boolean isLoved = quanZiApi.queryUserIsLove(publishId, userId);
            if (isLoved) {
                return loveCount;
            }
            //喜欢就是往comment集合中添加一条数据
            loveCount = quanZiApi.loveComment(publishId, userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return loveCount;
    }

    public Integer disLoveComment(String publishId) {
        Integer loveCount = null;
        try {
            Long userId = UserThreadLocal.get().getId();
            //如果没有被喜欢,就不能取消喜欢
            boolean isLoved = quanZiApi.queryUserIsLove(publishId, userId);
            if (!isLoved) {
                return loveCount;
            }
            //取消喜欢就是往comment集合中删除那条数据
            loveCount = quanZiApi.disLoveComment(publishId, userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return loveCount;
    }

    public Dynamic queryDynamic(String publishId) {
        Dynamic dynamic = new Dynamic();

        return dynamic;
    }
}